package com.martin.fastframe.ui.flow

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.martin.lib_base.interfaces.IRelease
import com.martin.lib_base.constant.ConstantKey
import com.martin.lib_base.impl.FlowBus
import com.martin.lib_base.impl.LiveDataBus
import com.martin.lib_base.impl.observeForKey
import com.martin.lib_base.ktx.loge
import com.martin.lib_base.utils.ReleaseUtil
import com.martin.lib_base.utils.addReleaseForKey
import dev.DevUtils
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class FlowModel : IRelease {

    @OptIn(DelicateCoroutinesApi::class)
    fun init() {
        FlowBus.with<String>(ConstantKey.VIDEO)
            .onEach {
                loge("收到视频消息 1 $it")
            }.launchIn(GlobalScope)
            .addReleaseForKey(this) {
                it.cancel()
            }
        FlowBus.with<String>(ConstantKey.VIDEO)
            .observeForKey(this) {
                loge("收到视频消息 2 $it")
            }

        LiveDataBus.with(ConstantKey.VIDEO)
            .observe(
                DevUtils.getTopActivity() as LifecycleOwner,
                Observer<Any> { t -> loge("LiveDataBus 收到视频消息 4 $t") }
                    .addReleaseForKey(this@FlowModel) {
                        LiveDataBus.with(ConstantKey.VIDEO).removeObserver(it)
                    })
    }

    override fun release() {
        ReleaseUtil.release(this)
    }

}